package com.leyou.gateway.filter;

import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.task.AppTokenHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 这个过滤器是为了在请求头中放入微服务自己的token
 */
@Slf4j
@Component
public class PrivilegeFilter implements GlobalFilter, Ordered {

    @Autowired
    private AppTokenHolder appTokenHolder;  //token保存在这个类中

    @Autowired
    private JwtProperties jwtProperties;    //存入请求头中的key在这个类中

    /**
     * 微服务将自己的token放入请求头中
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取token
        String token = appTokenHolder.getToken();
        //把token放入请求头中
        ServerHttpRequest newRequest = exchange.getRequest().mutate().header(jwtProperties.getApp().getHeaderName(), token).build();
        //重新生成一个新的交换机
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        //放入过滤器中
        return chain.filter(newExchange);
    }

    /**
     * 数值越小越先执行(要大于token权限(0))
     * @return
     */
    @Override
    public int getOrder() {
        return 6;
    }
}
